package message

import (
	"encoding/json"

	"bird/config"

	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
	sms "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/sms/v20210111"
)

type Repo interface {
	i()
	Send(phoneNumber string, content ...string) (res string, err error)
}

type smsRepo struct {
	client   *sms.Client
	sdkAppId string
	signName string
}

func New() (Repo, error) {
	client, err := smsConnect()

	if err != nil {
		return nil, err
	}
	cfg := config.Get().Sms

	return &smsRepo{
		client:   client,
		sdkAppId: cfg.SdkAppId,
		signName: cfg.SignName,
	}, nil
}

func smsConnect() (client *sms.Client, err error) {
	cfg := config.Get().Sms
	credential := common.NewCredential(cfg.SecretId, cfg.SecretKey)

	cpf := profile.NewClientProfile()

	client, err = sms.NewClient(credential, "ap-beijing", cpf)

	return
}

func (m *smsRepo) i() {}

func (m *smsRepo) Send(phoneNumber string, content ...string) (string, error) {
	request := sms.NewSendSmsRequest()
	request.SmsSdkAppId = common.StringPtr(m.sdkAppId)
	request.SignName = common.StringPtr(m.signName)
	request.TemplateId = common.StringPtr("1163272")
	request.TemplateParamSet = common.StringPtrs(content)
	request.PhoneNumberSet = common.StringPtrs([]string{"+86" + phoneNumber})

	response, err := m.client.SendSms(request)
	if err != nil {
		return "", err
	}

	b, _ := json.Marshal(response.Response)

	return string(b), nil
}
